package com.wswy.wzcx.ui.main.community

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.wswy.wzcx.R
import com.wswy.wzcx.model.Converter
import com.wswy.wzcx.model.topic.TopicModel
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.CBaseLoadingFragment
import com.wswy.wzcx.module.base.Func1
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.main.community.add.AddTopicActivity
import com.wswy.wzcx.utils.UiUtils
import kotlinx.android.synthetic.main.fragment_community.*


class CommunityFragment : CBaseLoadingFragment() {



    companion object {

        @JvmField val TAG = "bbs"


        @JvmStatic fun newInstance() = CommunityFragment()

    }


    private lateinit var llManager: LinearLayoutManager

    private lateinit var communityViewModel: CommunityViewModel
    private lateinit var  topicListAdapter:TopicListAdapter


    private var holderLoginCallback : Func1 = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_community,container,false)?.apply {
            //UiUtils.injectStatusBar(this)
        }
    }


    override fun getConfigure(): ILoadingView.LoadingConfigure = object : ILoadingView.SampleLoadingConfigure() {
        override fun getOnRetryClickListener(): View.OnClickListener {
            return View.OnClickListener {
                showLoading(true)
                communityViewModel.loadData(true)
            }
        }
    }

    override fun getLoadingFrameId(): Int {
        return R.id.fl_content
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        communityViewModel= provideViewModel(CommunityViewModel::class.java)
        communityViewModel.onCreate()

        llManager = LinearLayoutManager(context)
        recycler_view.layoutManager = llManager
        topicListAdapter = TopicListAdapter({

            communityViewModel.gotoLogin(recycler_view.context)

            holderLoginCallback = it

            null

        },View.OnClickListener{

            //startActivityForResult(Intent(it.context,AddTopicActivity::class.java), REQ_ADD_TOPIC)

            StatTools.sendClick(it.context,StatisticsId.bbs_issue_box)

            startActivity(Intent(it.context,AddTopicActivity::class.java))
        })

        recycler_view.adapter = topicListAdapter


        recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    trackTop()
                }
            }
        })


        refreshLayout.setOnRefreshListener {
            it.setEnableLoadMore(true)
            communityViewModel.loadData()

        }

        refreshLayout.setOnLoadMoreListener {

            if (communityViewModel.canLoadMore()){
                communityViewModel.loadMore()
            }else{
                it.finishLoadMore()
                it.setEnableLoadMore(false)
            }

        }

        fab.setOnClickListener {

            StatTools.sendClick(it.context,StatisticsId.bbs_issue_float)

            startActivity(Intent(it.context,AddTopicActivity::class.java))
        }


        fab_top.setOnClickListener {
            refreshLayout.finishLoadMore()
            recycler_view.stopScroll()
            llManager.scrollToPosition(0)

            hide()
        }

        initData()
    }


    private fun initData(){

        //用户登录
        communityViewModel.getUserLiveData().observe(this,android.arch.lifecycle.Observer {

            it?.run {

                holderLoginCallback?.invoke()

            }

        })

        //列表
        communityViewModel.getTopicListLiveData().observe(this,android.arch.lifecycle.Observer {

            it?.run {



                if (isOk()){

                    refreshLayout.finishRefresh(0)
                    showData()

                    if (this.data != null){
                        topicListAdapter.datas.clear()
                        topicListAdapter.datas.addAll(this.data)
                        topicListAdapter.notifyDataSetChanged()
                    }
                }else if (isFirst() && hasError()){
                    showError(VOMessage.create(null))
                }else if(hasError()){
                    refreshLayout.finishRefresh(0)
                }
            }
        })

        //加载
        communityViewModel.getTopicLoadMoreLiveData().observe(this,android.arch.lifecycle.Observer {

            it?.run {

                if (!inLoading()){
                    refreshLayout.finishLoadMore(0)
                }

                if (isOk()){

                    if (this.data != null){
                        topicListAdapter.datas.addAll(this.data)
                        topicListAdapter.notifyDataSetChanged()
                    }
                }

            }


        })

        //更新数量
        communityViewModel.getUpdateNumLiveData().observe(this, Observer {

            it?.toIntOrNull()?.run {

                if (this > 0) {

                    tv_update_num.postDelayed({
                        tv_update_num.visibility = View.VISIBLE
                        tv_update_num.text = getString(R.string.topic_update_num,this)
                    }, 500)

                    tv_update_num.postDelayed({
                        tv_update_num.visibility = View.GONE
                    }, 2000)

                }

            }

        })


        //贴子 新增 删除
        communityViewModel.getTopicChangeLiveData().observe(this, Observer {

            it?.run {


                when(first){
                    CommunityViewModel.TYPE_ADD -> {

                        topicListAdapter.datas.add(0,Converter.convert2TopicVO(second,true))
                        topicListAdapter.notifyItemInserted(1)

                    }

                    CommunityViewModel.TYPE_DELETE -> {
                        //贴子删除
                        val datas = topicListAdapter.datas

                        val first = llManager.findFirstVisibleItemPosition()

                        for (i in first until datas.size){
                            if (datas.getOrNull(i)?.model == second){

                                datas.removeAt(i)
                                topicListAdapter.notifyItemRemoved(i+1)
                                break
                            }
                        }

                    }


                    CommunityViewModel.TYPE_LIKE -> {
                        //贴子点赞

                        val datas = topicListAdapter.datas
                        val first = llManager.findFirstVisibleItemPosition()
                        for (i in first until datas.size){
                            if (datas.getOrNull(i)?.model == second){

                                datas.getOrNull(i)?.addLike(false)
                                topicListAdapter.notifyItemChanged(i+1)
                                break
                            }
                        }
                    }


                    CommunityViewModel.TYPE_ADD_COMMENT -> {
                        //添加评论

                        val datas = topicListAdapter.datas
                        val first = llManager.findFirstVisibleItemPosition()
                        for (i in first until datas.size){
                            if (datas.getOrNull(i)?.model == second){

                                datas.getOrNull(i)?.addReviewCount()
                                topicListAdapter.notifyItemChanged(i+1)
                                break
                            }
                        }
                    }

                }

                communityViewModel.changeConsumed()

            }

        })


        communityViewModel.loadData(true)

    }

    private fun trackTop(){
        if (llManager.findFirstVisibleItemPosition() > 0){
            show()
        }else{
            hide()
        }
    }

    private fun hide() {
//        fab_top.isEnabled = false
//        if (fab_top.alpha === 1f) {
//            fab_top.animate().alpha(0f).start()
//        }
        fab_top.hide()
    }


    private fun show() {

//        fab_top.isEnabled = true
//        if (fab_top.alpha === 0f) {
//            fab_top.animate().alpha(1f).start()
//        }
        fab_top.show()
    }



}